package com.qianlima.upload.domain.service;

import com.qianlima.upload.infrastructure.core.config.FileGlobalConfiguration;
import com.qianlima.upload.infrastructure.utils.FileUploadUtil;
import com.qianlima.upload.infrastructure.utils.HashUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @description: 文件上传基类
 * @author：allms
 * @date: 2023/3/22 15:26
 */
public abstract class BaseFileAbstract extends FileRepositorySupport {

    private static final String FILE_PRIVATE_KEY = "qianlima";
    @Resource
    protected FileUploadUtil fileUploadUtil;

    @Resource
    protected FileGlobalConfiguration fileGlobalConfiguration;

    public List<String> upload(List<MultipartFile> multipartFileList) throws IOException {
        try {
            List<String> fileUrlList = new ArrayList<>();
            // 支持多文件上传
            for (MultipartFile multipartFile : multipartFileList) {
                String relativePath = fileUploadUtil.uploadFile(multipartFile,
                        fileGlobalConfiguration.getLocal().getBucketName());
                String appUrl = fileGlobalConfiguration.getLocal().getUrl(false);
                fileUrlList.add(appUrl + relativePath);
            }
            return fileUrlList;
        } catch (IOException e) {
            throw e;
        }
    }

    protected String generateKeyShortCode(String input) {
        return HashUtils.sha256(HashUtils.md5(input.toLowerCase() + FILE_PRIVATE_KEY)).substring(0, 10);
    }

}
